package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class Server {
	private static final int SERVER_PORT = 6787;
	private ServerSocket serverSocket;
	
	public Server() throws IOException{
		serverSocket = new ServerSocket(SERVER_PORT);
	}
	
	void acceptConnection() throws IOException{
		while(!serverSocket.isClosed()){
			Socket socket = serverSocket.accept();
			new ServerWorker(socket).start();
		}
	}
	
	private class KeyboardListener extends Thread {
		public void run(){
			Scanner scanner = new Scanner(System.in);
			while(scanner.hasNext()){
				String command = scanner.next();
				if(command.equalsIgnoreCase("close")){
					try {
						serverSocket.close();
						break;
					} catch (IOException e) {
						e.printStackTrace();
						break;
					}
				}
			}
			scanner.close();
		}
	}
	
	public static void main(String args[]){
		Server server;
		try {
			server = new Server();
			server.new KeyboardListener().start();
			server.acceptConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
